import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import Login from '@/views/login.vue'
import Index from '@/views/index.vue'
// import { login } from '@/apis/user'
import Welcome from '@/views/welcome.vue'
import PostsList from '@/views/posts/postsList.vue'
import Postspublish from '@/views/posts/postspublish.vue'

const router = new VueRouter({
    routes: [
        {
            name: 'default',
            path: '/',
            redirect: { name: 'login' }
        },
        {
            name: 'login',
            path: '/login',
            component: Login
        },
        {
            name: 'index',
            path: '/index',
            component: Index,
            // 重定项的时候要使用name,如果在嵌套路由的时候,使用path,会被当成根路由来看待
            redirect: { name: 'welcome' },
            // 添加嵌套路由
            children: [
                {
                    name: 'welcome',
                    path: 'welcome',
                    component: Welcome
                },
                {
                    name: 'postsList',
                    path: 'postsList',
                    component: PostsList
                },
                {
                    name: 'postspublish',
                    path: 'postspublish',
                    component: Postspublish
                },
            ]
        },

    ]
})
// 添加导航守卫(任何路由跳转都要经过导航守卫)
router.beforeEach((to, from, next) => {
    // 如果当前跳转的目标是/login那么就去登录
    // 如果是其他页,则要判断是否有token,如果有则登录,如果没有就去/login登录
    // 逻辑:如果是去登录,那就去登录,登录以后查看是否要跳转到其他页,如果要跳转的话,就去看看有没有token,
    // 有的话就直接next(),没有的话就调回登录页,(专业术语叫重定向到登录页)
    if (to.path == '/login') {
        next()
    } else {
        let token = localStorage.getItem('heima_toutiao_houtai')
        if (token) {
            next()
        } else {
            next({ path: '/login' })
        }
    }
})
export default router